package com.pulse.common.utils.gzip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {


    public static String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }

        // 创建一个字节数组输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用 GZIPOutputStream 压缩数据
        try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(str.getBytes("UTF-8"));
        }
        // 将压缩后的字节数组转换为 Base64 字符串
        return Base64.getEncoder().encodeToString(out.toByteArray());
    }

    public static String decompress(String compressedStr) throws IOException {
        if (compressedStr == null || compressedStr.length() == 0) {
            return compressedStr;
        }

        // 将 Base64 字符串解码为字节数组
        byte[] compressedBytes = Base64.getDecoder().decode(compressedStr);
        // 创建一个字节数组输入流
        ByteArrayInputStream in = new ByteArrayInputStream(compressedBytes);
        // 使用 GZIPInputStream 解压缩数据
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (GZIPInputStream gzip = new GZIPInputStream(in)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzip.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
        // 将解压缩后的字节数组转换为字符串
        return out.toString("UTF-8");
    }

    public static void main(String[] args) {
        // 压缩
        try {
            String originalString = "This is a test string to be compressed using GZIP.";
            String compressedString = compress(originalString);
            System.out.println("Compressed String: " + compressedString);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 解压缩
        try {
            String compressedString = "H4sIAAAAAAAAAAvJyCxWAKJEhZLU4hKF4pKizLx0hZJ8haRUheT83IKi1OLi1BSF0mKQsHuUZ4AeACJ47lkyAAAA";
            String decompressedString = decompress(compressedString);
            System.out.println("Decompressed String: " + decompressedString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
